package com.john.booter.module.file.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.john.booter.domain.entity.File;
import com.john.booter.module.file.dao.FileDao;

@Repository
public class FileDaoImpl implements FileDao {
	
	@PersistenceContext
	private EntityManager em;

	@Override
	public void save(File file) {
		em.persist(file);
	}

	@Override
	public void delete(String id) {
		Query query = em.createQuery("delete from File t where t.id = ?1");
		query.setParameter(1, id);
		query.executeUpdate();
	}

	@Override
	public void deleteByState(String state) {
		Query query = em.createQuery("delete from File t where t.state = ?1");
		query.setParameter(1, state);
		query.executeUpdate();
	}
	
	@Override
	public void update(File file) {
		em.merge(file);
	}

	@Override
	public void updateState(String fileId, String state) {
		Query query = em.createQuery("update File set state = ?1 where id = ?2");
		query.setParameter(1, state);
		query.setParameter(2, fileId);
		query.executeUpdate();
	}
	
	@Override
	public List<File> findAll() {
		return em.createQuery("from File t", File.class).getResultList();
	}

	@Override
	public File findById(String id) {
		TypedQuery<File> query = em.createQuery("from File t where t.id = ?1", File.class); 
		query.setParameter(1, id);
		List<File> list = query.getResultList();
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<File> findByState(String state) {
		TypedQuery<File> query = em.createQuery("from File t where t.state = ?1", File.class); 
		query.setParameter(1, state);
		return query.getResultList();
	}

}
